package com.pro01.backend.service;

import com.pro01.backend.mapper.NotificationMapper;
import com.pro01.backend.pojo.Notification;
import com.pro01.backend.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NotificationService {

    @Autowired
    private NotificationMapper notificationMapper;


    // 发送通知
    public void sendNotification(Long receiverId, Long senderId, String type, String content, String link) {
        Notification notification = new Notification();
        notification.setUserId(receiverId);
        notification.setSenderId(senderId);
        notification.setType(type);
        notification.setContent(content);
        notification.setLink(link);
        notification.setStatus("UNREAD");

        notificationMapper.insertNotification(notification);
    }

    // 发送系统通知


    // 查询通知列表
    public PageResult<Notification> getNotifications(Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Notification> records = notificationMapper.selectNotifications(userId, offset, pageSize);
        int total = notificationMapper.countNotifications(userId);
        return new PageResult<>(total, records);
    }

    // 查询未读通知数量
    public int getUnreadNotificationCount(Long userId) {
        return notificationMapper.countUnreadNotifications(userId);
    }

    // 把通知标记已读
    public void markAsRead(Long notificationId, Long userId) {
        int result = notificationMapper.markNotificationAsRead(notificationId, userId);
        if (result == 0) {
            throw new RuntimeException("标记通知为已读失败，可能该通知不存在、已被删除，或者你没有权限操作");
        }
    }

    // 批量标记通知为已读
    public void markAllAsRead(Long userId) {
        int result = notificationMapper.markAllNotificationsAsRead(userId);
        if (result == 0) {
            // 不抛异常，允许用户没有未读通知
        }
    }


}
